package it.blueocean.acanto.platform.aop.dao;

import it.blueocean.acanto.platform.model.common.ABaseEntity;

import java.lang.reflect.Method;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.security.core.context.SecurityContextHolder;

public class AuditingStoreDaoInterceptor implements MethodBeforeAdvice
{
	private static Logger logger = null;

	public AuditingStoreDaoInterceptor()
	{
	}

	public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable
	{
		logger = LoggerFactory.getLogger(arg2.getClass());
		
		for (int i = 0; i < arg1.length; i++)
		{
			if(arg1[i] instanceof ABaseEntity)
			{
				ABaseEntity entity = (ABaseEntity) arg1[i];

				logger.info("Adding information to entity : " + entity);

				Object actualUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

				if(entity.getCreated() == null)
				{
					entity.setCreator(actualUser.toString());
					entity.setCreated(new Date());
				}

				entity.setModifier(actualUser.toString());
				entity.setModified(new Date());
			}
		}
	}

}